﻿using System;
using MongoDB.Bson;
using MongoDB.Driver.Core;
using MongoDB.Driver;
using System.Threading.Tasks;
using MongoDB.Bson.Serialization;
using System.Collections.Generic;

namespace KY.Mongo
{
    public class MongoRepository : IMongoRepository
    {
        public MongoClient client { get; set; }
        public IMongoDatabase database { get; set; }
        public IMongoCollection<BsonDocument> collection { get; set; }
        public void Setup()
        {
            client = new MongoClient("mongodb://127.0.0.1:27017");
            database = client.GetDatabase("antdesign");

        }

        public MongoRepository()
        {
            Setup();
        }



        public Task InsertAsync(MongoDTO dTO)
        {
            collection = database.GetCollection<BsonDocument>(dTO.CollectionName);
            return collection.InsertOneAsync(Serialize(dTO));
        }

        private BsonDocument Serialize(MongoDTO dto)
        {
            Dictionary<string, object> data = new Dictionary<string, object>();
            var jsonData = BsonSerializer.Deserialize<BsonDocument>(dto.JsonStr);
            data.Add(dto.Key, dto.Value);
            data.Add("Data", jsonData);
            return new BsonDocument(data);
        }

        public Task UpdateAsync(MongoDTO dTO)
        {
            var jsonData = BsonSerializer.Deserialize<BsonDocument>(dTO.JsonStr);
            collection = database.GetCollection<BsonDocument>(dTO.CollectionName);
            var builders = Builders<BsonDocument>.Filter;
            var filter = Builders<BsonDocument>.Filter.Eq(dTO.Key, dTO.Value);
            var update = Builders<BsonDocument>.Update.Set("Data", jsonData);
            return collection.UpdateOneAsync(filter, update);
        }

        public MongoDTO FindAsync(MongoDTO dTO)
        {
            var jsonData = BsonSerializer.Deserialize<BsonDocument>(dTO.JsonStr);
            collection = database.GetCollection<BsonDocument>(dTO.CollectionName);
            var builders = Builders<BsonDocument>.Filter;
            var filter = Builders<BsonDocument>.Filter.Eq(dTO.Key, dTO.Value);
            var result = collection.Find<BsonDocument>(filter).FirstOrDefault();
            dTO.JsonStr = result["Data"].ToJson();
            return dTO;
        }


    }
}
